/* autor Konjkov.VV@gmail.com */

#include <stdio.h>
#include <string.h>

#include "connect.h"
#include "common.h"

int syncctl_connect(char *server) {
SQLRETURN retcode;

    SQLAllocEnv( &env );
    SQLAllocConnect( env, &dbc );

    retcode = SQLConnect( dbc, server, SQL_NTS, NULL, 0, NULL, 0 );
    if ( retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO ) {
        SQLSetConnectOption( dbc, SQL_AUTOCOMMIT, SQL_TRUE );
//        SQLSetEnvAttr( dbc, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, -1);

//        SQLSMALLINT i;

//        SQLGetInfo(dbc, SQL_MAX_CATALOG_NAME_LEN, &i, 0, NULL);
//        SQLGetInfo(dbc, SQL_MAX_SCHEMA_NAME_LEN, &i, 0, NULL);
//        SQLGetInfo(dbc, SQL_MAX_TABLE_NAME_LEN, &i, 0, NULL);
//        SQLGetInfo(dbc, SQL_MAX_COLUMN_NAME_LEN, &i, 0, NULL);
//        SQLGetInfo(dbc, SQL_MAX_STATEMENT_LEN, &i, 0, NULL);

        SQLSetConnectAttr( dbc, SQL_ATTR_METADATA_ID, SQL_TRUE, -1);
    } else {
        syncctl_error( SQL_NULL_HSTMT, __FILE__, __LINE__ );
        SQLFreeConnect( dbc );
        SQLFreeEnv( env );
    }
    return 0;
}


int syncctl_disconnect() {

    SQLDisconnect( dbc );
    SQLFreeConnect( dbc );
    SQLFreeEnv( env );
    return 0;
}

int syncctl_error(HSTMT stmt, char *file, int line ) {
SQLCHAR         sql_state[SQL_SQLSTATE_SIZE];
SQLCHAR         message[SQL_MAX_MESSAGE_LENGTH];
SQLINTEGER      error_code;
SQLSMALLINT     req_size;

        SQLError( env, dbc, stmt, sql_state, &error_code, message, SQL_MAX_MESSAGE_LENGTH, &req_size);
        printf("SQL Error[Number: %i, State: %s]: %s in %s:%d\n", error_code, sql_state, message, file, line);
        return 0;
}
